package com.mimaxueyuan.disruptor.demo1;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

/**
 * @author: Kevin
 * @官网: 	www.mimaxueyuan.com
 * @Q Q群:	660567408
 * @Email:	mimaxueyuan@163.com
 * [每天进步一点点、人生带来大改变...]
 * [本代码对应视频地址:http://study.163.com/course/introduction/1004573050.htm]
 */
public class LongEventMain0 {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InterruptedException {
		// 初始化线程池-用户执行Consumer
		Executor executor = Executors.newCachedThreadPool();

		// 初始化EventFactory
		LongEventFactory factory = new LongEventFactory();

		// 初始化RingBuffer的大小,必须是2的指数
		int bufferSize = 1024;

		// 初始化RingBuffer
		Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(factory, bufferSize, executor);

		// 指定事件处理器
		disruptor.handleEventsWith(new LongEventHandler());

		// 开启Disruptor,开启所有线程,(此方法只能调用一次,并且所有的EventHandler必须在start之前添加,包括ExceptionHandler)
		disruptor.start();
		
		// 获取RingBuffer
		RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

		// 以下代码为模板化代码,怎样发布事件到RingBuffer
		// 获取下一个序号
		long sequence = ringBuffer.next();
		try {
			// 根据下一个序号获取Event
			LongEvent event = ringBuffer.get(sequence);
			// Do some work with the event.
			event.set(10000L);
			System.out.println("Main product -> " + event);
		} finally {
			// 发布序号(发布后可以被消费)
			ringBuffer.publish(sequence);
		}
	}

}
